package com.senyin.pathSearchUtil.service.impl;

import com.senyin.pathSearchUtil.common.BaseResponse;
import com.senyin.pathSearchUtil.common.ResultResponse;
import com.senyin.pathSearchUtil.mapper.FileInfosMapper;
import com.senyin.pathSearchUtil.model.FileInfos;
import com.senyin.pathSearchUtil.service.FileInfosService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

@Service
public class FileInfosServiceImpl implements FileInfosService {
    @Resource
    private FileInfosMapper mapper;

    @Transactional
    @Override
    public BaseResponse save(List<LinkedHashMap<String,Object>> list){
        mapper.createTable();
        mapper.deleteTable();
        for (LinkedHashMap<String,Object> fileInfos : list) {
            FileInfos fileInfo = new FileInfos();
            fileInfo.setFileName((String) fileInfos.get("FileName"));
            fileInfo.setFilePath((String) fileInfos.get("FilePath"));
            fileInfo.setFileType((String) fileInfos.get("FileType"));
            fileInfo.setFileSize((Double) fileInfos.get("FileSize"));
            fileInfo.setFileDate(getDate((String) fileInfos.get("FileDate")));
            int save = mapper.save(fileInfo);
            if (save <= 0){
                throw new RuntimeException("Failed to insert fileInfo.");
            }
        }
        return ResultResponse.success("success");
    }

    @Override
    public BaseResponse get() {
        List<FileInfos> fileInfos = mapper.get();
        if (fileInfos.size()<=0){
            return ResultResponse.error("存在无效数据或数据为空，读取失败。");
        }
        return ResultResponse.success(fileInfos);
    }

    private Date getDate(String fileDate){
        String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX";
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            OffsetDateTime offsetDateTime = OffsetDateTime.parse(fileDate, formatter);
            Date date = Date.from(offsetDateTime.toInstant());
            return  date;
        } catch (DateTimeParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}
